import { Schema, model } from 'mongoose'
import bcrypt from 'bcryptjs'

export const UserSchema = new Schema({
    email: {
        type: String,
        required: [true, 'EMAIL_REQUIRED'],
        unique: true,
        match: [/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/, 'INVALID_EMAIL']
    },
    passwordHash: {
        type: String,
        required: [
            function () {
                return !this.googleId
            },
            'PASSWORD_REQUIRED'
        ]
    },
    emailVerified: {
        type: Boolean,
        default: false
    },
    googleId: String,
    createdAt: {
        type: Date,
        default: Date.now
    }
})

// 添加密码比对方法
UserSchema.methods.comparePassword = async function(candidatePassword) {
  // 使用bcryptjs进行密码比对
  return await bcrypt.compare(candidatePassword, this.passwordHash)
}
// 添加复合索引
UserSchema.index({ email: 1, googleId: 1 })

// 密码哈希预处理
UserSchema.pre('save', async function (next) {
    if (!this.isModified('passwordHash')) return next()
    try {
        const salt = await bcrypt.genSalt(10)
        this.passwordHash = await bcrypt.hash(this.passwordHash, salt)
        next()
    } catch (error) {
        next(error)
    }
})

export const User = model('User', UserSchema)